import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "login" */ '../views/LoginView.vue')
  },{
    path: '/regist',
    name: 'regist',
    component: () => import(/* webpackChunkName: "regist" */ '../views/RegistView.vue')
  },{
    path: '/my',
    name: 'my',
    component: () => import(/* webpackChunkName: "my" */ '../views/MyView.vue'),
  }
]



const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token');
  const whiteList = ['/login', '/regist']
  if(token) {
    // 存在
    if(whiteList.includes(to.path)) {
      next('/my')
    } else {
      next()
    }
  } else {
    // 不存在
    if(whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
